<?php

namespace common\service;

use common\model\ReviewRequestNodeModel;
use common\model\ReviewRequestModel;
use common\model\VersionModel;
use common\model\EntityModel;
use common\model\TaskModel;
use support\SingletonTrait;

/**
 * 审片室服务
 */
class ReviewRoomService
{
    use SingletonTrait;

    /**
     * 查询播放列表信息
     * @param $taskVersionList
     * @return array
     */
    public function selectPlayListTaskVersionInfo($taskVersionList)
    {
        $sequenceModuleId = module_by_code('sequence')['id'];
        $shotModuleId = module_by_code('shot')['id'];
        $taskModuleId = module_by_code('task')['id'];
        $entityQueryFields = ['id', 'name', 'code', 'module_id', 'initial_episode_code', 'entity_id', 'entity_module_id', 'json', 'showings_number'];
        $taskIdList = array_column($taskVersionList, 'task_id');

        $taskIdRelations = ReviewTaskService::getInstance()->conversionInsideIdMap($taskIdList);
        foreach ($taskVersionList as &$taskVersionItem) {
            if (isset($taskIdRelations['a_to_b_map'][$taskVersionItem['task_id']])) {
                $taskVersionItem['task_id'] = $taskIdRelations['a_to_b_map'][$taskVersionItem['task_id']];
            }
        }
        $versionIdList = array_column($taskVersionList, 'version_id', 'task_id');
        $reviewRequestIdList = array_column($taskVersionList, 'review_request_id', 'version_id');
        $reviewRequestNodeIdList = array_column($taskVersionList, 'review_request_node_id', 'version_id');
        $taskIdList = array_column($taskVersionList, 'task_id');

        // 版本信息查询 已经通过的版本 或者是制片进行提交过 或者是当前提交版本
        // @update 2021年8月3日 不查询弃用的版本
        $versionFilter = [
            'module_id' => $taskModuleId, 'link_id' => ['IN', implode(',', $taskIdList)],
            'is_deprecate' => 'no',
        ];

        $versionsInfo = model(VersionModel::class)->where($versionFilter)->select();
        $mediaIdList = [];
        foreach ($versionsInfo as &$version) {
            $jsonFields = json_decode($version['json'], true);
            $version = array_merge($version, $jsonFields);
            $version['version_media'] = explode(',', $version['version_media'] ?? '');
            if (count($version['version_media'])) {
                $tmpMediaIdList = [];
                foreach ($version['version_media'] as $mediaId) {
                    if (intval($mediaId) > 0) {
                        $tmpMediaIdList[] = $mediaId;
                        $mediaIdList[$mediaId] = $mediaId;
                    }
                }
                $version['version_media'] = $tmpMediaIdList;
            }
        }
        $versionMediaList = MediaService::getInstance()->selectMediaParamMap($mediaIdList);
        // 查询审核信息
        $reviewRequestList = model(ReviewRequestModel::class)->where(['id' => ['IN', implode(',', $reviewRequestIdList)]])->select();
        $reviewRequestList = array_column($reviewRequestList, null, 'link_id');
        $reviewRequestNodeList = model(ReviewRequestNodeModel::class)->where(['id' => ['IN', implode(',', $reviewRequestNodeIdList)]])->select();
        $reviewRequestNodeList = array_column($reviewRequestNodeList, null, 'review_request_id');
        // 查询任务信息
        $taskQueryFields = [
            'task.id',
            'task.name',
            'task.code',
            'task.executor_tenant_id',
            'task.tenant_id',
            'task.entity_id',
            'task.entity_module_id',
            'task.department_id',
            'task.man_hour',
            'task.project_id',
            'task.step_type',
            'task.step_category_id',
            'task.step_id',
            'task.executor',
            'task.json',
            'entity.id',
            'entity.name',
            'entity.code',
            'entity.module_id',
            'entity.project_id',
            'entity.initial_episode_code',
            'entity.entity_id',
            'entity.entity_module_id',
            'entity.json',
            'entity.showings_number',
            'entity.director_star',
        ];
        $tasksInfo = model(TaskModel::class)
            ->where(['task.id' => ['IN', implode(',', $taskIdList)]])
            ->join('entity on task.entity_id = entity.id')
            ->order('entity.initial_episode_code ASC,entity.showings_number ASC,entity.name ASC')
            ->field(build_complex_query_fields($taskQueryFields, '__'))
            ->select();

        $sequenceIdList = [];
        $executorUserIdList = [];
        $statusIdList = [];
        $episodeCodeGroupedByProject = [];
        foreach ($tasksInfo as &$task) {
            $taskData = separate_complex_query_data($task, '__');
            if (!isset($episodeCodeGroupedByProject[$taskData['entity']['project_id']])) {
                $episodeCodeGroupedByProject[$taskData['entity']['project_id']] = [$taskData['entity']['initial_episode_code']];
            } elseif (!in_array($taskData['entity']['initial_episode_code'], $episodeCodeGroupedByProject[$taskData['entity']['project_id']])) {
                $episodeCodeGroupedByProject[$taskData['entity']['project_id']][] = $taskData['entity']['initial_episode_code'];
            }
            $task = $taskData['task'];
            $taskJson = json_decode($task['json'] ?? '{}', true);
            unset($task['json']);
            $task['task_status'] = $taskJson['task_status'] ?? 0;
            $statusIdList[$task['task_status']] = $task['task_status'];
            $task['entity'] = $taskData['entity'];
            if (!empty($task['entity'])) {
                $task['entity'] = CommonService::appendJsonFields($task['entity'], 'json');
                if ($task['entity']['module_id'] === $shotModuleId && $task['entity']['entity_id'] > 0) {
                    $sequenceIdList[$task['entity']['entity_id']] = $task['entity']['entity_id'];
                }
            }
            $executorUserIdList[$task['executor']] = $task['executor'];
        }
        unset($executorUserIdList[0], $statusIdList[0]);
        // 剧集场次map查询
        $sceneDataMap = [];
        if (!empty($episodeCodeGroupedByProject)) {
            $episodeIdCodeMap = [];
            $episodeMap = EpisodeService::getInstance()->getMultipleProjectEpisodes($episodeCodeGroupedByProject);
            foreach ($episodeMap as $episodeList) {
                foreach ($episodeList as $episode) {
                    $episodeIdCodeMap[$episode['id']] = $episode['code'];
                }
            }
            if (!empty($episodeIdCodeMap)) {
                $sceneData = EpisodeShowingsNumberTreeService::getInstance()->sceneSelect(['episode_id' => ['-in', implode(',', array_keys($episodeIdCodeMap))]]);
                foreach ($sceneData as $sceneDataItem) {
                    $episodeCode = $episodeIdCodeMap[$sceneDataItem['episode_id']];
                    $sceneDataMap[$episodeCode . '_' . strtolower($sceneDataItem['name'])] = $sceneDataItem;
                }
            }
        }

        // 执行人查询
        $executorUserList = [];
        if (!empty($executorUserIdList)) {
            $executorUserList = UserService::getInstance()->selectLocalUserList(['id' => ['IN', implode(',', $executorUserIdList)]], ['id', 'name', 'avatar']);
            $executorUserList = array_column($executorUserList, null, 'id');
        }
        // 状态查询
        $statusList = [];
        if (!empty($statusIdList)) {
            $statusList = StatusService::getInstance()->getList(['id' => ['IN', implode(',', $statusIdList)]], 'id,name,code,color');
            $statusList = array_column($statusList, null, 'id');
        }
        $sequenceList = [];

        if (!empty($sequenceIdList)) {
            $sequenceList = model(EntityModel::class)->field($entityQueryFields)->where(['id' => ['IN', implode(',', $sequenceIdList)]])->select();
            $sequenceList = array_map(function ($item) {
                return CommonService::appendJsonFields($item, 'json');
            }, $sequenceList);
            $sequenceList = array_column($sequenceList, null, 'id');

        }
        $versionsInfo = array_group_by($versionsInfo, 'link_id');

        // 组装列表数据
        foreach ($tasksInfo as &$task) {
            $task['executor'] = $executorUserList[$task['executor']] ?? null;
            $task['task_status'] = $statusList[$task['task_status']] ?? null;
            $task['is_outside'] = $task['executor_tenant_id'] !== $task['tenant_id'] ? 'yes' : 'no';
            $task['sort_name'] = 'default';
            if (!empty($task['entity']) && $task['entity']['entity_id'] > 0 && $task['entity']['entity_module_id'] === $sequenceModuleId) {
                $task['entity']['sequence'] = $sequenceList[$task['entity']['entity_id']] ?? null;
                $task['sort_name'] = isset($task['entity']['sequence']) ? $task['entity']['sequence']['name'] . '_' . $task['entity']['name'] : 'default';
            }
            $task['entity']['scene'] = $sceneDataMap[$task['entity']['initial_episode_code'] . '_' . strtolower($task['entity']['showings_number'])] ?? null;
            $task['entity']['scene_id'] = !empty($task['entity']['scene']['id']) ? $task['entity']['scene']['id'] : 0;
            unset($task['entity']['scene']);
            $task['version_list'] = $versionsInfo[$task['id']] ?? [];
            $activeVersionId = $versionIdList[$task['id']] ?? 0;
            $task['version_list'] = array_sort_by($task['version_list'], 'number', 'desc', false);
            if (empty($task['version_list']) || $activeVersionId === 0) {
                $reviewStatus = 'wait_submit';
            } else {
                $latestVersionReviewRequest = $reviewRequestList[$activeVersionId] ?? null;
                if (empty($latestVersionReviewRequest)) {
                    $reviewStatus = 'wait_submit';
                } else {
                    // 是否已经审核
                    if ($latestVersionReviewRequest['is_reviewed'] === 'yes') {
                        if ($latestVersionReviewRequest['is_pass'] === 'yes') {
                            $reviewStatus = 'reviewed';
                        } else {
                            // 不通过 需要判断是不是能看到
                            $latestVersionReviewRequestNode = $reviewRequestNodeList[$latestVersionReviewRequest['id']] ?? null;
                            if (empty($latestVersionReviewRequestNode)) {
                                $reviewStatus = 'wait_submit';
                            } else if ($latestVersionReviewRequestNode['is_terminate'] === 'yes') {
                                $reviewStatus = 'wait_submit';
                            } else {
                                $reviewStatus = 'reviewed';
                            }
                        }
                    } else {
                        // 整个版本未审核完
                        $latestVersionReviewRequestNode = $reviewRequestNodeList[$latestVersionReviewRequest['id']] ?? null;
                        if (empty($latestVersionReviewRequestNode)) {
                            $reviewStatus = 'wait_submit';
                        } else {
                            if ($latestVersionReviewRequestNode['is_terminate'] === 'yes'
                                || ($latestVersionReviewRequestNode['is_active'] === 'no' && $latestVersionReviewRequestNode['is_reviewed'] === 'no')) {
                                /**
                                 * 提前终结的
                                 * 上一个环节还没审核结束
                                 *
                                 * 显示为待提交
                                 */
                                $reviewStatus = 'wait_submit';
                            } else {
                                $reviewStatus = $latestVersionReviewRequestNode['is_reviewed'] === 'yes' ? 'reviewed' : 'wait_review';
                            }
                        }
                    }
                }
            }
            $task['review_status'] = $reviewStatus;

            $needReview = false;
            $canReviewVersionId = 0;
            foreach ($task['version_list'] as &$version) {
                $version['param'] = json_decode($version['param'], true);
                $version['review_request_id'] = $reviewRequestIdList[$version['id']] ?? 0;
                $version['review_request'] = $reviewRequestList[$version['id']] ?? null;
                $version['review_request_node'] = $reviewRequestNodeList[$version['review_request_id']] ?? null;
                if (!$needReview && !empty($version['review_request']) && $version['review_request']['is_reviewed'] === 'no' && !empty($version['review_request_node']) && $version['review_request_node']['is_active'] === 'yes' && $version['review_request_node']['is_reviewed'] === 'no') {
                    $needReview = true;
                    $canReviewVersionId = $version['id'];
                    $version['can_review'] = 'yes';
                }
                $version['is_select_default'] = $activeVersionId && $activeVersionId == $version['id'] ? 'yes' : 'no';
                foreach ($version['version_media'] as &$mediaId) {
                    $mediaId = $versionMediaList[$mediaId] ?? null;
                }
            }
            $task['need_review'] = $needReview;
            $task['can_review_version_id'] = $canReviewVersionId;
        }
        return $tasksInfo;
    }

}
